package com.zhentao.filter;


import com.zhentao.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Component
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        System.err.println("admin过滤器"+request.getPath());

        //判断是否为登录路径
        if (request.getURI().getPath().contains("/login") || request.getURI().getPath().contains("/api-docs")){
            return chain.filter(exchange);
        }

        //获取token
        String token = request.getHeaders().getFirst("token");

        System.out.println("token："+token);

        //如果为空则不放行
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //校验token
        try {
            //获取token
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);

            System.err.println(claimsBody);

            //获取当前登录的userId
            Object id = claimsBody.get("id");
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("appID", id + "");
            }).build();
            //重置header
            exchange.mutate().request(serverHttpRequest).build();

        }catch (Exception e){

            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
